import time
import requests
import asyncio
import aiohttp

URLS = [
    'https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg',
    'https://www2.autoimg.cn/newsdfs/g30/M01/3C/E2/120x90_0_autohomecar__ChcCSV2BBICAUntfAADjJFd6800429.jpg',
    'https://www3.autoimg.cn/newsdfs/g26/M0B/3C/65/120x90_0_autohomecar__ChcCP12BFCmAIO83AAGq7vK0sGY193.jpg'
]

# ---------- 同步版本 ----------
def sync_download():
    print("\n开始同步下载")
    start = time.perf_counter()

    for url in URLS:
        print("同步请求:", url)
        response = requests.get(url)
        file_name = 'sync_' + url.rsplit('_')[-1]
        with open(file_name, 'wb') as f:
            f.write(response.content)

    end = time.perf_counter()
    print(f"同步下载总耗时：{end - start:.2f} 秒")


# ---------- 异步版本 ----------
async def fetch(session, url):
    print("异步请求:", url)
    async with session.get(url) as response:
        content = await response.read()
        file_name = 'async_' + url.rsplit('_')[-1]
        with open(file_name, 'wb') as f:
            f.write(content)


async def async_download():
    print("\n开始异步下载")
    start = time.perf_counter()

    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in URLS]
        await asyncio.gather(*tasks)

    end = time.perf_counter()
    print(f"异步下载总耗时：{end - start:.2f} 秒")


async def main():  # 你必须定义这个 main()
    print("\n开始异步下载")
    start = time.perf_counter()
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in URLS]
        await asyncio.gather(*tasks)
    end = time.perf_counter()
    print(f"异步下载总耗时：{end - start:.2f} 秒")

if __name__ == '__main__':
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        loop.run_until_complete(main())  # ✅ 这行调用的 main()，必须在前面定义了
    finally:
        loop.run_until_complete(asyncio.sleep(0.1))
        loop.close()
